//
//  ViewController.swift
//  RecordDemo
//
//  Created by yuanyue on 2018/4/25.
//  Copyright © 2018年 yuanyue. All rights reserved.
//

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var recoder : AVAudioRecorder? = {
        let url = URL(string: "/Users/yuanyue/Desktop/test/test.caf")
        
        let dic  = [
            // 编码格式
            AVFormatIDKey : NSNumber(value: Int32(kAudioFormatLinearPCM)),
            // 采样率
            AVSampleRateKey : NSNumber(value: 11025.0),
            // 通道数
            AVNumberOfChannelsKey : NSNumber(value: 2),
            // 录音质量
            AVEncoderAudioQualityKey : NSNumber(value: Int32(AVAudioQuality.min.rawValue))
            
        ]
        
        
        do {
            let recoder: AVAudioRecorder = try AVAudioRecorder(url: url!, settings: dic)
            // 准备录音
            recoder.prepareToRecord()
            return recoder
        } catch {
            return nil
        }
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

    
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("开始录音")
        // 开始录音
//        recoder?.record()
        
        // 从什么时间点开始录音（需要手动结束录音）
//        recoder?.record(atTime: (recoder?.deviceCurrentTime)! + 3);
        
//        // 从现在开始录多久
//        recoder?.record(forDuration: 3)
//
//        // 从哪个时间开始录，录多久
//        recoder?.record(atTime: (recoder?.deviceCurrentTime)!, forDuration: 3)
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("结束录音")
        if (recoder?.currentTime)! < Double(2) {
            print("录音文件太短")
            recoder?.stop()
            recoder?.deleteRecording()
            return
        }
        recoder?.stop()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

